import { Component, OnInit } from '@angular/core';
import {NzMessageService, NzModalSubject} from "ng-zorro-antd";
import {DeptService} from "../dept.service";

class Dept {
    id;
    pid;
    name;
    sort;
    enable;
    remark;
}

@Component({
  selector: 'app-dept-edit',
  templateUrl: './dept-edit.component.html',
  styleUrls: ['./dept-edit.component.scss']
})
export class DeptEditComponent implements OnInit {

    i;

    _item: Dept = new Dept();
    _options = null;
    _loaded = false;
    _value: any[] = [];

    _changeValue(value) {
        this._item.pid = this._value[this._value.length - 1];
    }

    _addIsLeafField(list) {
        list.forEach((val, idx, array) => {
            if (val.children) {
                this._addIsLeafField(val.children);
            } else {
                val.isLeaf = true;
            }
        });
    }

    _setParent(cur) {
        if (cur.parent) {
            this._value.unshift(cur.parent);
            this._setParent(cur.parent);
        }
    }

    save() {
        this.service.save(this._item).subscribe(() => {
            this.nzMessage.success('保存成功');
            this.subject.next(true);
            this.close();
        });
    }

    close() {
        this.subject.destroy();
    }

    constructor(private subject: NzModalSubject,
                private nzMessage: NzMessageService,
                private service: DeptService) {
    }

    ngOnInit() {
        this._setParent(this.i);
        this._item.id = this.i.id;
        if (this._item.id > 0) {
            this._item.pid = this.i.pid;
            this._item.name = this.i.name;
            this._item.sort = this.i.sort;
            this._item.enable = this.i.enable;
            this._item.remark = this.i.remark;
        } else {
            this._item.pid = 0;
            this._item.enable = false;
        }
        this.service.getTree().subscribe(data => {
            this._addIsLeafField(data);
            this._options = data;
            this._loaded = true;
        });
    }


}
